// eslint-disable-next-line import/no-cycle
import { uploadVideo } from './newUpload';
import playVideo from './playVideo';

const $ = window.$;
// 视频最大限制，因为iPhone有视频自动压缩功能，因此限制其大小为10m

const CDNURL = `${window.location.protocol}//media.weipaitang.com/`;

function handleErr(err, errTip) {
    // "File extension error."
    switch (err.code) {
        case -601: {
            return '不支持此视频格式';
        }
        case -200: {
            return '网络错误，请重新上传';
        }
        case 400: {
            return '上传出错，请重新上传';
        }
        default: {
            return `上传出错，请重新上传: ${JSON.stringify(err, null, 4)} ${errTip || ''}`;
        }
    }
}

/**
 * 获取视频播放地址，封面图，video key
 * @param {string} [key='']
 * @param {any} [cdnurl=CDNURL]
 * @returns
 */
function getVideoInfo(key = '', cdnurl = CDNURL) {
    const newKey = (key || '').split('.')[0];
    let videoUrl = `${cdnurl}${key}`;
    // 如果key不包含后缀，表示视频已在转码或者转码成功
    if (!key.includes('.')) {
        videoUrl = `${cdnurl}wpt_${key}`;
    }

    return {
        videoCover: `${cdnurl}wpt_cover_${newKey}`,
        videoUrl,
        video: key,
    };
}

// 获取视频时长
function getVideoDuration(key, callback) {
    $.ajax({
        url: `${CDNURL}${key}?avinfo&t=${Date.now()}`,
        success(res) {
            res.format ? callback(+res.format.duration) : callback();
        },
        error() {
            callback();
        },
    });
}

function waitCover(key, cdnUrl, success, fail) {
    const newKey = key.lastIndexOf('.') > -1 ? key.slice(0, key.lastIndexOf('.')) : key;

    let time = 0;
    // 最大请求次数
    const MAX_TIMES = 15;
    function ajax() {
        if (time > MAX_TIMES) {
            return fail && fail();
        }

        const videoCover = `${cdnUrl}wpt_cover_${newKey}`;

        return $.ajax({
            url: `${videoCover}?imageInfo&t=${Date.now()}`,
            dataType: 'json',
            success(res) {
                console.log('视频封面图片加载成功');
                if (res.format) {
                    success && success(videoCover, res);
                } else {
                    setTimeout(() => {
                        time += 1;
                        ajax();
                    }, 2000);
                }
            },
            error() {
                console.log('视频封面图片加载失败');
                setTimeout(() => {
                    time += 1;
                    ajax();
                }, 2000);
            },
        });
    }
    ajax();
}

const DEFAULT_TRANSLATE_URL = WPT.Util.handleApi('/v1.0/qiniu/to-persistent-fop-l?actions=vframe&bType=sale', {
    useEnv: true,
});
function codeTranslate(key, callback, codeTranslateUrl = DEFAULT_TRANSLATE_URL) {
    WPT.postData(codeTranslateUrl, JSON.stringify({ key }), res => {
        if (res.code == 0) {
            callback && callback();
        } else {
            WPT.Modal.alert(res.msg, { style: { color: '#AB3B3A' } });
            window.reportError({ key, uri: WPT.userinfo.userinfoUri, codeTranslateUrl });
        }
    });
}

/**
 * [getVideoSrc 获取视频地址]
 * @method getVideoSrc
 * @param  {[type]}    $dom [description]
 * @return {[type]}         [description]
 */
function getVideoSrc($dom) {
    $dom = $($dom);
    return $dom.data('src') || $dom.data('video-src');
}

WPT.playVideo = WPT.playVideo || playVideo;
WPT.getVideoSrc = WPT.getVideoSrc || getVideoSrc;

export {
    // 播放
    playVideo,
    // 获取视频信息
    getVideoInfo,
    // 等待封面图生成
    waitCover,
    // url cdn media.weipaitang.com
    CDNURL,
    // 处理错误，返回错误信息
    handleErr,
    // 上传视频
    uploadVideo,
    // 视频截图
    codeTranslate,
    // 视频时长
    getVideoDuration
};
